package com.zhihuichongcheng.application.ui.openclass.activity;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.smartlib.cmnObject.ui.NoScrollListView;
import com.smartlib.cmnObject.util.DateUtil;
import com.smartlib.cmnObject.util.DialogUtil;
import com.smartlib.cmnObject.util.FileUtil;
import com.smartlib.cmnObject.util.GsonUtil;
import com.smartlib.cmnObject.util.LogUtil;
import com.smartlib.cmnObject.util.ToastOpt;
import com.yirimao.video.JCVideoPlayerStandard;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.base.BaseActivity;
import com.zhihuichongcheng.application.bean.cricle.CommentBean;
import com.zhihuichongcheng.application.bean.openclass.OpenClassBean;
import com.zhihuichongcheng.application.bean.openclass.SubCategory;
import com.zhihuichongcheng.application.constant.Constants;
import com.zhihuichongcheng.application.constant.NetworkAPI;
import com.zhihuichongcheng.application.net.HttpCallback;
import com.zhihuichongcheng.application.ui.cricle.adapter.CommentAdapter;
import com.zhihuichongcheng.application.util.OpenFiles;
import com.zhihuichongcheng.application.util.SystemBarTintManager;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by 3water on 2016/10/29.
 */

public class OpenClassDetailActivity extends BaseActivity implements View.OnClickListener {
    private ImageView mImImage, mImDownLoad, mImDownloadType;
    private RelativeLayout mRlImg;
    private JCVideoPlayerStandard mVideo;
    private TextView mTvTitle, mTvType, mTvClassCategory, mTvContent, mTvStudyNum, mTvCommentNum, mTvSend, mTvFileSize, mTvTopType;
    private NoScrollListView mRcvComment;
    private CommentAdapter mAdapter = null;
    private List<CommentBean> mListData = new ArrayList<>();
    private EditText mEtInput;
    private ImageView mImMp3;
    private String id;
    private RelativeLayout mRlDownload;
    private ProgressBar mBar;
    private long oldPro = 0;
    private String path;
    private OpenClassBean openClassBean;
    private TextView mTvDownloadTitle, mTvDownloadSize, mTvDownloadProgress;
    private Runnable mRunnbale;
    private DownloadManager mDownloadManager;
    private long mDownloadId;
    private boolean isPrepar = false;
    private MediaPlayer mMediaPlayer;
    private boolean isStart = true;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    private boolean flagFileDownloaded;

    private ContentObserver downloadObserver = new ContentObserver(mHandler) {
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            LogUtil.logD("===========");
            DownloadManager.Query query = new DownloadManager.Query().setFilterById(mDownloadId);
            Cursor cursor = null;
            try {
                cursor = mDownloadManager.query(query);
                if (cursor != null && cursor.moveToFirst()) {
                    long downloadedBytes = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                    long totalBytes = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                    LogUtil.logD("downloadedBytes======" + downloadedBytes + "/n  " + "totalBytes=" + totalBytes);
                    mTvDownloadSize.setText(FileUtil.getFormatSize(downloadedBytes) + "/" + FileUtil.getFormatSize(openClassBean.getFileSize()));
                    if (downloadedBytes == totalBytes) {
                        mRlDownload.setVisibility(View.GONE);
                        flagFileDownloaded = true;
                        mImDownLoad.setImageResource(R.drawable.ic_play);
                        ToastOpt.createToast(getContext(), "下载完毕");
                        getContentResolver().unregisterContentObserver(downloadObserver);
                    } else {
                        mBar.setProgress((int) ((downloadedBytes) * 100 / totalBytes));
                        mRlDownload.setVisibility(View.VISIBLE);
                    }
                    mTvDownloadProgress.setText(mBar.getProgress() + "%");
                }
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_openclass_detail);
        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(R.color.activity_color);//通知栏所需颜色
        initView();
        initData();
    }

    private void initView() {
        mMediaPlayer = new MediaPlayer();
        mImMp3 = (ImageView) findViewById(R.id.im_mp3);
        mImMp3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isStart) {
                    mImMp3.setBackgroundResource(R.drawable.jc_pause_normal);
                    isStart = false;
                    if (isPrepar) {
                        mMediaPlayer.start();
                    }
                } else {
                    mImMp3.setBackgroundResource(R.drawable.ic_video_open);
                    isStart = true;
                    if (isPrepar) {
                        mMediaPlayer.pause();
                    }
                }
            }
        });
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                isPrepar = true;
                if (!isStart) {
                    mMediaPlayer.start();
                }
            }
        });
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mImMp3.setBackgroundResource(R.drawable.ic_video_open);
            }
        });
        mImDownloadType = (ImageView) findViewById(R.id.im_download_type);
        mTvDownloadTitle = (TextView) findViewById(R.id.tv_download_title);
        mTvDownloadSize = (TextView) findViewById(R.id.tv_download_size);
        mTvDownloadProgress = (TextView) findViewById(R.id.tv_download_progress);
        mRlDownload = (RelativeLayout) findViewById(R.id.rl_download);
        mBar = (ProgressBar) findViewById(R.id.progress_bar);
        mTvTopType = (TextView) findViewById(R.id.tv_Top_type);
        mTvFileSize = (TextView) findViewById(R.id.tv_file_size);
        mImDownLoad = (ImageView) findViewById(R.id.im_download);
        mRlImg = (RelativeLayout) findViewById(R.id.rl_img);
        mVideo = (JCVideoPlayerStandard) findViewById(R.id.video);
        mBar = (ProgressBar) findViewById(R.id.progress_bar);
        mEtInput = (EditText) findViewById(R.id.et_input);
        mTvSend = (TextView) findViewById(R.id.tv_send);
        mImImage = (ImageView) findViewById(R.id.im_image);
        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mTvType = (TextView) findViewById(R.id.tv_type);
        mTvClassCategory = (TextView) findViewById(R.id.tv_class_category);
        mTvContent = (TextView) findViewById(R.id.tv_class_troduction_content);
        mTvStudyNum = (TextView) findViewById(R.id.tv_study_num);
        mTvCommentNum = (TextView) findViewById(R.id.tv_comment_num);
        mRcvComment = (NoScrollListView) findViewById(R.id.rcv_comment);
        mAdapter = new CommentAdapter(mContext);
        mRcvComment.setAdapter(mAdapter);
        mRcvComment.setFocusable(false);
        mTvSend.setOnClickListener(this);
        mImImage.setOnClickListener(this);
        mImDownLoad.setOnClickListener(this);
        mEtInput.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mEtInput.setCursorVisible(true);
                return false;
            }
        });
    }

    private void initData() {
        mEtInput.setCursorVisible(false);
        String title = "";
        Intent intent = getIntent();
        if (intent != null && intent.hasExtra("title")) {
            title = intent.getStringExtra("title");
        }
        if (intent != null && intent.hasExtra("id")) {
            id = intent.getStringExtra("id");
        }
        setTitle(title);
        loadData();
        loadComment();
    }

    private void loadData() {
        DialogUtil.showLoadDiadlog(mContext);
        final HashMap<String, String> params = new HashMap<>();
        params.put("token", mUser.getToken());
        params.put("openClassId", id);
        mManager.post(NetworkAPI.Openclass_detail, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                DialogUtil.dismiss(mContext);

                openClassBean = GsonUtil.praseFromStringToBean(value, OpenClassBean.class);
                mTvTitle.setText(openClassBean.getTitle());
                SubCategory category = openClassBean.getOpenClassCategory();
                if (category != null) {
                    mTvType.setText(category.getCategoryName());
                }
                mBar.setMax(100);
                mTvClassCategory.setText(openClassBean.getContentType());
                mTvStudyNum.setText(openClassBean.getVisitCount());
                mTvContent.setText(openClassBean.getSummary());
                if (openClassBean.getContentType().equals("mp4")) {
                    mVideo.setVisibility(View.VISIBLE);
                    mImDownLoad.setVisibility(View.GONE);
                    mImImage.setVisibility(View.GONE);
                    mVideo.thumbImageView.setScaleType(ImageView.ScaleType.FIT_XY);
                    Glide.with(mContext).load(R.drawable.ic_openclass_video_defalut).into(mVideo.thumbImageView);
                    setImRight(R.drawable.ic_download_list, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!flagFileDownloaded)
                                downFile();
                        }
                    });
                    checkFileDownloadStatus();
                    if (flagFileDownloaded)
                        mVideo.setUp(path, "");
                    else
                        mVideo.setUp(openClassBean.getContentUrl(), "");
                } else if (openClassBean.getContentType().equals("mp3")) {
                    mTvTopType.setVisibility(View.VISIBLE);
                    mImDownLoad.setVisibility(View.GONE);
                    mTvTopType.setVisibility(View.VISIBLE);
                    mImMp3.setVisibility(View.VISIBLE);
                    mImImage.setVisibility(View.VISIBLE);
                    Glide.with(mContext).load(R.drawable.ic_openclass_music_defalut).into(mImImage);
                    mMediaPlayer.setVolume(3.0f, 1.0f);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            mMediaPlayer.reset();//把各项参数恢复到初始状态
                            try {
                                mMediaPlayer.setDataSource(openClassBean.getContentUrl());
                                mMediaPlayer.prepare();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                } else if (openClassBean.getContentType().equals("gif")) {
                    mVideo.setVisibility(View.GONE);
                    mImDownLoad.setVisibility(View.GONE);
                    mImImage.setVisibility(View.VISIBLE);
                    Glide.with(mContext).load(openClassBean.getContentUrl()).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).placeholder(R.drawable.ic_openclass_image_defalut).into(mImImage);
                } else if (openClassBean.getContentType().equals("png") || openClassBean.getContentType().equals("jpg") || openClassBean.getContentType().equals("jpeg") || openClassBean.getContentType().equals("bmp")) {
                    mVideo.setVisibility(View.GONE);
                    mImDownLoad.setVisibility(View.GONE);
                    mImImage.setVisibility(View.VISIBLE);
                    Glide.with(mContext).load(openClassBean.getContentUrl()).placeholder(R.drawable.ic_openclass_image_defalut).into(mImImage);
                } else {
                    if (openClassBean.getContentType().equals("pdf")) {
                        Glide.with(mContext).load(R.drawable.ic_openclass_pdf_defalut).into(mImImage);
                        Glide.with(mContext).load(R.drawable.ic_coordination_pdf).into(mImDownloadType);
                    } else if (openClassBean.getContentType().equals("doc")) {
                        Glide.with(mContext).load(R.drawable.ic_openclass_doc_defalut).into(mImImage);
                        Glide.with(mContext).load(R.drawable.ic_coordination_doc).into(mImDownloadType);
                    } else if (openClassBean.getContentType().equals("numbers")) {
                        Glide.with(mContext).load(R.drawable.ic_openclass_xcls_defalut).into(mImImage);
                        Glide.with(mContext).load(R.drawable.ic_coordination_xlcs).into(mImDownloadType);
                    } else if (openClassBean.getContentType().equals("xlsx")) {
                        Glide.with(mContext).load(R.drawable.ic_openclass_xcls_defalut).into(mImImage);
                        Glide.with(mContext).load(R.drawable.ic_coordination_xlcs).into(mImDownloadType);
                    } else if (openClassBean.getContentType().equals("rar") | openClassBean.getContentType().equals("zip")) {
                        Glide.with(mContext).load(R.drawable.ic_openclass_other_defalut).into(mImImage);
                        Glide.with(mContext).load(R.drawable.ic_coordination_zip).into(mImDownloadType);
                    } else if (openClassBean.getContentType().equals("ppt")) {
                        Glide.with(mContext).load(R.drawable.ic_openclass_ppt_defalut).into(mImImage);
                        Glide.with(mContext).load(R.drawable.ic_coordination_ppt).into(mImDownloadType);
                    } else {
                        Glide.with(mContext).load(R.drawable.ic_openclass_other_defalut).into(mImImage);
                        Glide.with(mContext).load(R.drawable.ic_coordination_other).into(mImDownloadType);
                    }
                    checkFileDownloadStatus();
                    if (flagFileDownloaded)
                        mImDownLoad.setImageResource(R.drawable.ic_play);
                    mImDownLoad.setVisibility(View.VISIBLE);
                    mVideo.setVisibility(View.GONE);
                    mImImage.setVisibility(View.VISIBLE);
//                    mImImage.setBackgroundColor(getResources().getColor(R.color.color_5C8AC9));
                    mTvTopType.setVisibility(View.VISIBLE);
//                    Glide.with(mContext).load(openClassBean.getContentUrl()).asGif().into(mImImage);
                }
                mTvFileSize.setText(FileUtil.getFormatSize(openClassBean.getFileSize()));
            }

            @Override
            public void onFailure(String value) {

            }
        }, params);
    }

    private void loadComment() {
        HashMap<String, String> params = new HashMap<>();
        params.put("token", mUser.getToken());
        params.put("openClassId", id);
        mManager.post(NetworkAPI.Openclass_Detail_comment, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                mListData = GsonUtil.paraeFromStringToList(value, CommentBean.class);
                if (mListData != null && mListData.size() > 0) {
                    mTvCommentNum.setText("学员评论(" + mListData.size() + ")");
                } else {
                    mTvCommentNum.setText("学员评论(0)");
                }
                mAdapter.setData(mListData);
                mAdapter.notifyDataSetChanged();

            }

            @Override
            public void onFailure(String value) {
                mTvCommentNum.setText("学员评论(0)");
            }
        }, params);
    }

    /**
     * 下载文件
     */
    private void downFile() {
        String url = openClassBean.getContentUrl();
        String[] strs = url.split("/");
        mDownloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse(openClassBean.getContentUrl());
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setNotificationVisibility(View.VISIBLE);
        request.setDestinationInExternalPublicDir("/ThreeWaterbeijing/download/", strs[strs.length - 1]);
        mDownloadId = mDownloadManager.enqueue(request);
        getContentResolver().registerContentObserver(Uri.parse("content://downloads/my_downloads"), true, downloadObserver);
    }

    private void checkFileDownloadStatus() {
        String url = openClassBean.getContentUrl();
        String[] strs = url.split("/");
        LogUtil.logD(strs[strs.length - 1]);
        mTvTopType.setVisibility(View.VISIBLE);
        path = Constants.Const_Cache_Dir + "/" + strs[strs.length - 1];
        File file = new File(path);
        if (file.exists() && file.length() == openClassBean.getFileSize()) {
            flagFileDownloaded = true;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_send:
                final String content = mEtInput.getText().toString();
                if (!TextUtils.isEmpty(content)) {
                    HashMap<String, String> params = new HashMap<>();
                    params.put("token", mUser.getToken());
                    params.put("content", content);
                    params.put("openClassId", id);
                    mManager.post(NetworkAPI.Openclass_detail_addComment, new HttpCallback() {
                        @Override
                        public void onSuccess(int code, String value, String msg) {
                            if (code == 1) {
                                CommentBean commentBean = new CommentBean();
                                commentBean.setContent(content);
                                commentBean.setUser(mUser);
                                //计算时间
                                String date = DateUtil.transferLongToDate("yyyy年MM月dd日 HH:mm:ss", System.currentTimeMillis());
                                commentBean.setCreateTime(date);
                                mAdapter.addItem(commentBean);
                                mAdapter.notifyDataSetChanged();
                                mEtInput.setText("");
                            }
                        }

                        @Override
                        public void onFailure(String value) {

                        }
                    }, params);
                    hideKeyboard(mEtInput);
                } else {
                    ToastOpt.createToast(mContext, "请输入评论内容");
                }


                break;
            case R.id.im_download:
                if (flagFileDownloaded) {
                    OpenFiles.openFile(this, path);
                    return;
                }
                downFile();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMediaPlayer != null) {
            mMediaPlayer.reset();
            mMediaPlayer.release();
        }
        getContentResolver().unregisterContentObserver(downloadObserver);
    }
}
